// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <nebula/core/finger_printable.h>
#include <turbo/log/logging.h>

namespace nebula::detail {

    FingerPrintAble::~FingerPrintAble() {
        delete fingerprint_.load();
        delete metadata_fingerprint_.load();
    }

    template<typename ComputeFingerprint>
    static const std::string &load_fingerprint(std::atomic<std::string *> *fingerprint,
                                              ComputeFingerprint &&compute_fingerprint) {
        auto new_p = new std::string(std::forward<ComputeFingerprint>(compute_fingerprint)());
        // Since fingerprint() and metadata_fingerprint() return a *reference* to the
        // allocated string, the first allocation ever should never be replaced by another
        // one.  Hence the compare_exchange_strong() against nullptr.
        std::string *expected = nullptr;
        if (fingerprint->compare_exchange_strong(expected, new_p)) {
            return *new_p;
        } else {
            delete new_p;
            DKCHECK_NE(expected, nullptr);
            return *expected;
        }
    }

    const std::string &FingerPrintAble::load_fingerprint_slow() const {
        return load_fingerprint(&fingerprint_, [this]() { return compute_fingerprint(); });
    }

    const std::string &FingerPrintAble::load_metadata_fingerprint_slow() const {
        return load_fingerprint(&metadata_fingerprint_,
                               [this]() { return compute_metadata_fingerprint(); });
    }
}  // namespace nebula::detail